/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snail.Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import snail.hibernate.util.HibernateUtil;
import snail.model.Article;
import snail.model.User;
import snail.model.UserRating;

/**
 *
 * @author viktor
 */
public class RateUserServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                out.println("error.Du är inte inloggad");
            } else {


                int articleId = Integer.parseInt(request.getParameter("id"));
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                session.beginTransaction();
                Article article = (Article) session.load(Article.class, articleId);
                boolean positive = false;
                if (request.getParameter("pos").equals("1")) {
                    positive = true;
                }

                if (article == null) {
                    out.println("error.Auktionen har blivit borttagen");
                } else {

                    UserRating ur = new UserRating();
                    ur.setArticle(article);
                    ur.setRatedUser(article.getCreatorUser());
                    ur.setRatingUser(user);
                    ur.setIsPositive(positive);
                    //ur.setUserId(article.getCreatorUser().getUserId());
                    //ur.setByUserId(user.getUserId());
                    
                    session.save(ur);
                    session.getTransaction().commit();

                    out.println("Din säljarbedömning har registrerats");
                }
            }
        } catch (NumberFormatException ex) {
            out.println("error.Inte ok");
        }/* catch (Exception ex) {
            out.println("error.Nu gick något skapligt fel." + ex.getMessage());
        }*/ finally {
            out.close();
        }
    }
}
